package com.liuh.fram.handle;

import java.util.HashMap;

import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.liuh.fram.err.LocalException;
import com.liuh.fram.err.LocalException.ErrorType;
import com.liuh.fram.util.EncryptKit;

/**
 * @note 响应处理
 * @author liuh
 * */
public abstract class ResponseHandle extends HttpBaseHandle {

	/**
	 * @note 处理响应
	 * @author liuh
	 * */
	public abstract String parseResponse(String action, String data)
			throws Exception;

	/**
	 * @note action 转为枚举
	 * @author liuh
	 * */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Object buildActionHandle(String action, Class cls) {
		Object actionHandle = null;
		try {
			actionHandle = Enum.valueOf(cls, action);
			return actionHandle;
		} catch (Exception e) {
			// 匹配action失败
			throw new LocalException(ErrorType.noAction);
		}
	}

	/**
	 * @note 封装响应结果
	 * @author liuh
	 * */
	public String buildJson(String codeVal, Object msgVal) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", codeVal);
		map.put("msg", msgVal);
		return JsonKit.toJson(map);
	}

	/**
	 * @note 输出响应结果
	 * @author liuh
	 * */
	public String responseResult(String action, String data) throws Exception {
		String data2 = filterJson(data);
		String json = parseResponse(action, data2);
		if (StrKit.isBlank(json)) {
			// outJson为null
			throw new LocalException(ErrorType.defaultErr);
		}
		return EncryptKit.compress_base64(json);
	}
}
